package com.itstherules.jmsunit.queuemanager.webspheremq;

import java.net.URI;
import java.net.URISyntaxException;

import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;

import com.ibm.mq.jms.JMSC;
import com.ibm.mq.jms.MQQueueConnectionFactory;
import com.itstherules.jmsunit.queuemanager.BaseQueueManager;

public final class WebSphereMQQueueManager extends BaseQueueManager {

	public WebSphereMQQueueManager(String host, int port, String queueManager, String channel) throws JMSException {
		MQQueueConnectionFactory factory = new MQQueueConnectionFactory();
		factory.setHostName(host);
		factory.setPort(port);
		factory.setTransportType(JMSC.MQJMS_TP_CLIENT_MQ_TCPIP);
		factory.setQueueManager(queueManager);
		factory.setChannel(channel);
		connection = factory.createQueueConnection();
		session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
		connection.start();
	}

	public WebSphereMQQueueManager(String uri) throws JMSException {
		this(createUri(uri));
	}

	public WebSphereMQQueueManager(URI uri) throws JMSException {
		this(uri.getHost(), uri.getPort(), getQueueManager(uri.getPath()), getChannel(uri.getPath()));
	}
	
	private static String getChannel(String uri) {
		int slashIndex = uri.lastIndexOf("/");
		String channel = null;
		if (slashIndex <= uri.length()) {
			channel = uri.substring(slashIndex+1);
		}
		return channel;
	}

	private static URI createUri(String uri) {
		try {
			return new URI(uri);
		} catch (URISyntaxException e) {
			throw new IllegalArgumentException("The URI is not well formed: " + uri);
		}
	}
	
	private static String getQueueManager(String uri) {
		int slashIndex = uri.lastIndexOf("/");
		String queueManager = null;
		if (slashIndex <= uri.length()) {
			queueManager = uri.substring(1, slashIndex);
		}
		return queueManager;
	}
	
	
	public final MessageConsumer getMessageConsumerWithMessageID(String queue, String messageId) throws JMSException {
		String selector = "JMSMessageID = '" + messageId + "'";
		return session.createConsumer(this.createQueue(queue), selector);
	}
}
